package db;

import java.sql.*;

/**
 * @author Nathan Petryk (nathanp@indeed.com)
 */
class JDBCTemplate {

    private final Connection con;

    JDBCTemplate(Connection con) {
        this.con = con;
    }

    int insert(String sql, Object... params) throws SQLException {
        PreparedStatement stmnt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        setStatementParams(stmnt, params);

        int affected = stmnt.executeUpdate();

        ResultSet rs = stmnt.getGeneratedKeys();
        if(rs.next()) {
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();

            if(colCount > 0) {
                return Integer.parseInt( rs.getString(1) );
            }
        }

        return -1;
    }

    ResultSet select(String sql, Object... params) throws SQLException {
        PreparedStatement stmnt = con.prepareStatement(sql);
        setStatementParams(stmnt, params);

        return stmnt.executeQuery();
    }

    private static void setStatementParams(PreparedStatement stmnt, Object... params) throws SQLException {
        if(params != null)
        for(int i=0; i<params.length; i++)
            stmnt.setObject(i+1, params[i]);
    }
}
